package com.wys.mall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.wys.common.constant.AuthServerConstant;
import com.wys.common.exception.BizCodeEnum;
import com.wys.common.utils.MyStrUtil;
import com.wys.common.utils.R;
import com.wys.common.vo.MemberResponseVo;
import com.wys.mall.auth.feign.MemberFeignService;
import com.wys.mall.auth.feign.ThirdServiceService;
import com.wys.mall.auth.vo.UserLoginVo;
import com.wys.mall.auth.vo.UserRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Package com.wys.mall.auth.controller
 * @Author charlin
 * @Version: v1.0
 * @Date 2021-07-0510:34
 * @Copyright: 2021 www.wyscha.com Inc. All rights reserved.
 */
@Controller
public class LoginController {

    @Autowired
    private ThirdServiceService thirdServiceService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping({"/login.html", "/", "/loginPage"})
    public String loginPage(HttpSession session){
        Object loginUser = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(loginUser != null){
            return "redirect:http://mall.com";
        }
        return "login";
    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes attributes, HttpSession session) {
        R login = memberFeignService.login(vo);
        if (login.getCode() == 0) {
            MemberResponseVo data = login.getData("data", new TypeReference<MemberResponseVo>() {});
            session.setAttribute(AuthServerConstant.LOGIN_USER, data);
            return "redirect:http://mall.com";
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", login.getData("msg", new TypeReference<String>(){}));
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.mall.com/login.html";
        }

    }

    @ResponseBody
    @GetMapping({"/sms/sendcode"})
    public R sendCode(@RequestParam("phone") String phone) {
        //TODO 1、接口防刷
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (MyStrUtil.isNotEmpty(redisCode)) {
            Long saveTime = Long.parseLong(redisCode.split("_")[1]);
            //和不前系统时间比较, 60秒内定能再发
            if (System.currentTimeMillis() - saveTime < 60 * 1000) {
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMessage());
            }
        }

        String code = UUID.randomUUID().toString().replace("-", "").replaceAll("[a-zA-Z]", "").substring(0, 5);
        String saveCode = code + "_" + System.currentTimeMillis();
        //2.验证码检验 保存10分钟
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, saveCode, 10, TimeUnit.MINUTES);
        thirdServiceService.sendCode(phone, code);
        return R.ok();
    }

    /**
     * @param vo
     * @param result
     * @param model
     * @param attributes 重定向带数据
     * @return
     */
    @PostMapping({"/register"})
    public String register(@Valid UserRegisterVo vo, BindingResult result, Model model, RedirectAttributes attributes) {
        //如果有错误回到注册页面
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            attributes.addFlashAttribute("errors", errors);
            //效验出错回到注册页面
            return "redirect:http://auth.mall.com/reg.html";
        }
        //1、效验验证码
        String code = vo.getCode();
        //获取存入Redis里的验证码
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (MyStrUtil.isNotEmpty(redisCode)) {
            //截取字符串
            if (code.equals(redisCode.split("_")[0])) {
                //删除验证码;令牌机制
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                //验证码通过，真正注册，调用远程服务进行注册
                R register = memberFeignService.regist(vo);
                if (register.getCode() == 0) {
                    //成功
                    return "redirect:http://auth.mall.com/login.html";
                } else {
                    //失败
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", register.getData("msg", new TypeReference<String>() {
                    }));
                    attributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.mall.com/reg.html";
                }

            } else {
                //效验出错回到注册页面
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                attributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.mall.com/reg.html";
            }
        } else {
            //效验出错回到注册页面
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.mall.com/reg.html";
        }
    }
}
